package servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.BaseServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.Integer.parseInt;

@WebServlet("/userlogin.do")
public class UserServlet extends BaseServlet {
    private static final Logger logger = LoggerFactory.getLogger(UserServlet.class);
    private UserService userService = new UserServiceImpl();
    public String login(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        String login = request.getParameter("login");
        String id = null;
        String phone = null;
        String email = null;
        String em = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
        String ph = "^[1][3578]\\d{9}$";
        if(login.matches(em)){
            email = login;
        }else if(login.matches(ph)){
            phone = login;
        }else {
            id = login;
        }
        HttpSession session = request.getSession();
        User user = null;
        String password = request.getParameter("password");
        try {
            if (id != null) {
                user = userService.findUserById(parseInt(id));
            } else if (email != email) {
                user = userService.findUserByEmail(email);
            } else if (phone != null) {
                user = userService.findUserByPhone(phone);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (user != null) {
            if (user.getPassword().equals(password)) {
                logger.info("登录用户为:"+user.getName());
                session.setAttribute("user", user);
                return "r:xiaomi/index.html";
            }
        }
        return "r:xiaomi/index.html";
    }

    /**
     * 验证用户是否登录
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void review(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        if(user!=null){
           user.setPassword(null);
            String jsonString = JSONArray.toJSONString(user);
           out.write(jsonString);
        }else {
            User user1 = new User();
            user1.setName("none");
            String jsonString = JSONArray.toJSONString(user1);
            out.write(jsonString);
        }
        out.close();
    }

    /**
     * 更新用户信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void updateUser(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String Id = req.getParameter("id");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        User user = new User(Integer.parseInt(Id),name,password,phone,email);
        boolean flag = userService.updateUser(user);
        resp.setContentType("text/plain;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        if(flag){
            out.write("true");
            HttpSession session = req.getSession();
            session.setAttribute("user",user);
        }else{
            out.write("false");
        }
        out.close();
    }

    public void findAllUsers(HttpServletRequest request,HttpServletResponse response) throws IOException {
        List<User> users = userService.findAllUser();
        Map map = new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",users.size());
        map.put("data",users);
        response.getWriter().write(JSON.toJSONString(map));
    }
}
